﻿<style scoped>
  .el-menu--horizontal>.el-menu-item {
    height: 40px;
    line-height: 40px;
    padding: 0 10px;

  }
</style>
<template>
  <div>
    <el-row>
      <el-form size="small"  style="box-sizing:border-box;width:100%;padding-bottom:10px;" label-width="90px">
        <custom-field-form-item readonly :data="this.paramVersion" :fields="paramVersionFields">
          <el-button type="success" size="small" v-if="this.checkPermission('common_param:record') && paramVersion.state!='publish'" :disabled="isLoading" @click="save">保存</el-button>
          <el-button type="primary" size="small" v-if="this.checkPermission('common_param:record')" :disabled="paramVersion.state=='publish'||isLoading" @click="publish">发布</el-button>
          <el-button type="primary" size="small" v-if="this.checkPermission('common_param:record')" :disabled="paramVersion.state!='publish'||isLoading" @click="unPublish">取消发布</el-button>
        </custom-field-form-item>
      </el-form>
    </el-row>

    <el-tabs v-model="activeTab" v-loading="isLoading" type="border-card" lazy>

      <el-tab-pane label="成本数据" name="unit-cost-price">
        <record-table v-loading="loadingState.unitCost" ref="unit_cost_table" key="unit_cost_table"
                      :readonly="readonly" :max-height="pageHeight" border-color="#ccc"
                      v-if="unitCostList" :data="unitCostList" :columns="unitCostColumns"/>
      </el-tab-pane>

      <el-tab-pane label="税费数据" name="param-taxation">
        <record-table v-loading="loadingState.taxation" ref="taxation_table" key="taxation_table" border-color="#ccc"
                      :readonly="readonly" :max-height="pageHeight-115" :showIndex="true" style="text-align: center"
                      v-if="taxationDataList" :data="taxationDataList" :columns="taxationColumns">
        </record-table>
      </el-tab-pane>

      <el-tab-pane label="固定参数" name="param-fixed">
        <record-table v-loading="loadingState.fixed" ref="fixed_table" key="param-fixed"
                      :readonly="readonly" :max-height="pageHeight-115" border-color="#ccc"
                      v-if="fixedCostList" :data="fixedCostList"
                      :showIndex="true"
                      :columns="[
                          {id:'name',name:'参数项',readonly:true},
                          {id:'unit',name:'单位',type:'meta',source:'unit-type',readonly:true},
                          {id:'value',name:'值'}]">
        </record-table>
      </el-tab-pane>

      <el-tab-pane label="基准收益率" name="param-irr">
        <record-table v-loading="loadingState.irr" ref="irr_table" key="irr_table"
                      :readonly="readonly" :max-height="pageHeight-115" border-color="#ccc"
                      v-if="baseIrrList" :data="baseIrrList" :showIndex="true"
                      :columns="[
                          {id:'name',name:'参数项',readonly:true},
                          {id:'unit',name:'单位',type:'meta',source:'unit-type',readonly:true},
                          {id:'value',name:'值'}]">
        </record-table>
      </el-tab-pane>

      <el-tab-pane label="操作成本调整系数" name="param-2fixed">
        <record-table v-loading="loadingState.fixed" ref="fixed_table" key="param-fixed"
                      :readonly="readonly" :max-height="pageHeight-115" border-color="#ccc"
                      v-if="yearRelatedList" :data="yearRelatedList" :showIndex="true"
                      :columns="yearRelatedColumns" >
        </record-table>
      </el-tab-pane>
    </el-tabs>
  </div>

</template>

<script>

  export default {
    name: "ParamPublish",
    $$route: {
      meta: {title: '公共参数详情'},
    },
    props: {
      pageHeight: {},
    },
    data() {
      return {
        readonly:false,
        paramVersion: {},
        paramVersionFields:[
          {id: 'name', name: '名称', colSpan: 8,disabled:true},
          {id: 'publishTime', name: '发布时间', component:'date-picker',disabled:true, colSpan: 6},
          {id: 'state', name: '状态', component:{id:'meta-select',type:'param-version-state'},disabled:true, colSpan: 4},
        ],
        loadingState: {
          unitCost: false,
          taxation: false,
          fixed: false,
          irr:false,
          yearRelated:false,
        },
        isLoading: false,
        activeTab: 'unit-cost-price',
        unitCostMap:{},
        officeList:[],
        unitCostColumns:[
          {id:"rowIndex",name:"序号",width:50,verticalMerge:true,readonly:true,fixed:true},
          {id:"costType",name:"成本参数",width: 110,verticalMerge:true,readonly:true,fixed:true},
          {id:"costItem",name:"成本项",width: 150,readonly:true,fixed:true},
          {id:"costUnit",name:"单位",width: 120,readonly:true,fixed:true},
        ],
        unitCostList: [
          {rowIndex:1,costType:"单井定额",costItem:"单井定额", code:"operateCostStandard", costUnit:"万元/油气井数"},
          {rowIndex:2,costType:"吨油定额",costItem:"吨油定额", code:"oilQuotaStandard", costUnit:"元/吨油"},
          {rowIndex:3,costType:"固定可变",costItem:"固定成本", code:"fixedCost", costUnit:"万元/油气井数"},
          {rowIndex:3,costType:"固定可变",costItem:"可变成本", code:"variableCost", costUnit:"元/吨油（元/万方）"},
          {rowIndex:4,costType:"成本构成",costItem:"采出作业费", code:"miningOperationPrice", costUnit:"万元/油井数"},
          {rowIndex:4,costType:"成本构成",costItem:"驱油物注入费", code:"waterInjectionPrice", costUnit:"元/方水"},
          {rowIndex:4,costType:"成本构成",costItem:"稠油热采费",code:"heavyOilThRecPrice",costUnit:"元/吨蒸汽"},
          {rowIndex:4,costType:"成本构成",costItem:"油气处理费",code:"oilGasProcessPrice",costUnit:"元/吨液"},
          {rowIndex:4,costType:"成本构成",costItem:"轻烃回收费",code:"condensateRecyclePrice",costUnit:"万元/油井数"},
          {rowIndex:4,costType:"成本构成",costItem:"井下作业费",code:"underWellOperationPrice",costUnit:"万元/油井数"},
          {rowIndex:4,costType:"成本构成",costItem:"测井试井费",code:"wellTestPrice",costUnit:"万元/油井数"},
          {rowIndex:4,costType:"成本构成",costItem:"天然气净化费",code:"gasPurificationPrice",costUnit:"元/千立方米"},
          {rowIndex:4,costType:"成本构成",costItem:"维护及修理费",code:"repairPrice",costUnit:"万元/油井数"},
          {rowIndex:4,costType:"成本构成",costItem:"运输费",code:"transferPrice",costUnit:"万元/总井数"},
          {rowIndex:4,costType:"成本构成",costItem:"其他辅助作业费",code:"otherAuxiliaryPrice",costUnit:"万元/总井数"},
          {rowIndex:4,costType:"成本构成",costItem:"厂矿管理费",code:"factoryMineManagePrice",costUnit:"万元/总井数"},
        ],
        taxationColumns:[
          {id:"name",name:"项目",verticalMerge:true,readonly:true},
          {id:"unit",name:"单位",readonly:true},
          {id:"value",name:"数值"},
        ],
        taxationDataList:[
          {id:"oilValueAddedTaxRate",name:"原油增值税率",unit:"%",value:""},
          {id:"gasValueAddedTaxRate",name:"天然气增值税率",unit:"%",value:""},
          {id:"otherValueAddedTaxRate",name:"其他产品增值税率",unit:"%",value:""},
          {id:"cityConstructionTaxRate",name:"城市维护建设税率",unit:"%",value:""},
          {id:"educationSurchargeRate",name:"教育费附加税率",unit:"%",value:""},
          {id:"resourceTaxRate",name:"资源税率",unit:"%",value:""},
          {id:"incomeTaxRate",name:"所得税率",unit:"%",value:""},
        ],
        fixedCostList:[
          {id:"potionAmortisePeriod",name:"三元药剂摊销年限",unit:"年",value:""},
          {id:"iaAmortisePeriod",name:"无形资产摊销年限",unit:"年",value:""},
          {id:"otherAssetsAmortisePeriod",name:"其他资产摊销年限",unit:"年",value:""},
          {id:"loanRepaymentPeriod",name:"借款偿还期",unit:"年",value:""},
          {id:"fixedAssetBorrowRatio",name:"固定资产借款比例",unit:"%",value:""},
          {id:"disposalFeeRatio",name:"弃置费提取比例",unit:"%",value:""},
          {id:"longTermLoanInterestRate",name:"长期贷款利率",unit:"%",value:""},
          {id:"liquidBorrowInterestRate",name:"流动资金借款利率",unit:"%",value:""},
          {id:"liquidBorrowInterestRatio",name:"流动资金借款比例",unit:"%",value:""},
          {id:"liquidOfBusinessRatio",name:"流动资金占经营成本比例",unit:"%",value:""},
          {id:"costInputTaxOfOptRatio",name:"成本进项税占操作成本比例",unit:"%",value:""},
          {id:"unitSellCost",name:"单位销售及管理费用",unit:"%",value:""},
          {id:"surplusReserveRatio",name:"法定盈余公积金",unit:"%",value:""},
          {id:"exchangeRate",name:"汇率",unit:"人民币/美元",value:""},
          {id:"tonToBarrelRatio",name:"吨桶比",unit:"桶/t",value:""},
          {id:"oilGasEquivalent",name:"油气当量",unit:"方/吨",value:""},
          {id:"condensateEquivalent",name:"凝析油当量",unit:"吨凝析油/吨油",value:""},
          {id:"otherManageCostConventional",name:"其他管理费（常规）",unit:"元/吨油",value:""},
          {id:"otherManageCostDeApportion",name:"其他管理费（扣分摊）",unit:"元/吨油",value:""},
          {id:"otherManageCostGround",name:"其他管理费（地面评价）",unit:"万元/人·年",value:""},
          {id:"gasManageCostConventional",name:"天然气其他管理费（常规）",unit:"元/万方",value:""},
          {id:"gasManageCostDeApportion",name:"天然气其他管理费（扣分摊）",unit:"元/万方",value:""},
          {id:"gasManageCostGround",name:"天然气其他管理费（地面评价）",unit:"万元/人·年",value:""},
          {id:"mineralResourcesComprate",name:"矿业权出让收益率",unit:"%",value:""},
          {id:"businessCostRatio",name:"营业费率",unit:"%",value:""},
          {id:"safetyCostRatioOil",name:"安全生产费用（油）",unit:"元/吨",value:""},
          {id:"safetyCostRatioGas",name:"安全生产费用（气）",unit:"元/千方",value:""},
        ],
        baseIrrList:[
          {id:"conventional_oil_and_gas",name:"常规油气",unit:"%",value:""},
          {id:"special_oil_and_gas",name:"特殊油气",unit:"%",value:""},
          {id:"coalbed_gas",name:"煤层气",unit:"%",value:""},
          {id:"shale_gas",name:"页岩气",unit:"%",value:""},
          {id:"tight_gas",name:"致密气",unit:"%",value:""},
          {id:"tight_oil",name:"致密油",unit:"%",value:""},
          {id:"shale_oil",name:"页岩油",unit:"%",value:""},
          {id:"oil_shale_and_oil_sand_mines",name:"油页岩及油砂矿",unit:"%",value:""},
        ],
        yearRelatedColumns:[{id:'name',name:'项目',width:180,readonly:true}],
        yearRelatedList:[{id:"operateCostAdjustFactor",name:"集团规定操作成本调整系数"}],
      }
    },
    mounted() {
      this.loadParamVersion(this.$route.query.id);
    },
    methods: {
      loadParamVersion: function(id) {
        this.isLoading = true;
        this.$get("/settings/common_param_version/info/"+id,{},async (response) => {
          this.paramVersion = response.data;
          if (this.paramVersion.state == 'publish') {
            this.readonly = true;
          }else {
            this.readonly = false;
          }
          if (!this.checkPermission('common_param:record')) {
            this.readonly =true;
          }
          await this.init();
        },(response)=>{
          this.isLoading = false;
        });
      },
      init: async function() {
        await this.loadUnitCostData();
        this.loadFixData();
        this.loadBaseIrrData();
        await this.loadYearRelatedData();
      },
      loadUnitCostData: async function(){
        this.loadingState.unitCost = true;
        let officeResponse = await this.$getHttpPromise("/company/tree_by_code", {code:"DQYT"});
        let officeList = officeResponse.data[0].children.filter((item)=>{return item.type!='research'  && item.type!=null});
        this.officeList = officeList;
        let response = await this.$getHttpPromise("/settings/common_unit_cost/data", {
          versionId:this.paramVersion.id,
          pageSize: -1
        });
        let dataMap = {};
        if (response.data && response.data.length > 0) {
          for (let item of response.data) {
            dataMap[item.companyId] = item;
          }
        }
        let columns =  [
          {id:"rowIndex",name:"序号",width:50,verticalMerge:true,readonly:true,fixed:true},
          {id:"costType",name:"成本参数",verticalMerge:true,readonly:true,fixed:true},
          {id:"costItem",name:"成本项",width: 150,readonly:true,fixed:true},
          {id:"costUnit",name:"单位",readonly:true,fixed:true},
        ];
        let dataList = JSON.parse(JSON.stringify(this.unitCostList));
        for(let companyInfo of officeList) {
          let companyId = companyInfo.id;
          columns.push({id:companyId,name:companyInfo.shortName,width:90});

          for (let i = 0; i < dataList.length; i++) {
            let unitCostInfo = dataList[i];
            let companyData = dataMap[companyId];
            if(!companyData || !companyData[unitCostInfo.code] ){
              unitCostInfo[companyId] = '';
            }else{
              unitCostInfo[companyId] = companyData[unitCostInfo.code] + '';
            }
          }
        }
        this.unitCostColumns = columns;
        this.unitCostList = dataList;
        this.loadingState.unitCost = false;
      },
      loadFixData:function(){
        this.loadingState.unitCost = true;
        this.loadingState.taxation = true;
        this.$get("/settings/common_fixed/data",{versionId:this.paramVersion.id, pageSize: -1}, (response) => {
          let data = {};
          if (response.data && response.data.length > 0) {
            data = response.data[0];
          }
          let taxationDataList = [];
          for (let item of this.taxationDataList) {
            let row = {};
            row.id = item.id;
            row.name = item.name;
            row.unit = item.unit;
            if (data[row.id]) {
              row.value = data[item.id] + '';
            } else {
              row.value = '';
            }
            taxationDataList.push(row);
          }
          this.taxationDataList = taxationDataList;

          let fixedCostList = [];
          for (let item of this.fixedCostList) {
            let row = {};
            row.id = item.id;
            row.name = item.name;
            row.unit = item.unit;
            if (data[row.id]) {
              row.value = data[item.id] + '';
            } else {
              row.value = '';
            }
            fixedCostList.push(row);
          }
          this.fixedCostList = fixedCostList;
        },()=>{
          this.loadingState.unitCost = false;
          this.loadingState.taxation = false;
        });
      },
      loadBaseIrrData:function(){
        this.loadingState.irr = true;
        this.$get("/settings/common_base_irr/data",{versionId:this.paramVersion.id, pageSize: -1}, (response) => {
          let dataList = response.data;
          let dataMap = {};
          if (dataList && dataList.length > 0) {
            for (let item of dataList) {
              dataMap[item.poolType] = item.value;
            }
          }
          let baseIrrList = [];
          for (let item of this.baseIrrList) {
            let row = {};
            row.id = item.id;
            row.name = item.name;
            row.unit = item.unit;
            if (dataMap[row.id]) {
              row.value = dataMap[row.id] + '';
            } else {
              row.value = '';
            }
            baseIrrList.push(row);
          }
          this.baseIrrList = baseIrrList;
        },()=>{
          this.loadingState.irr = false;
        });
      },
      loadYearRelatedData: async function(){
        this.loadingState.yearRelated = true;
        let response = await this.$getHttpPromise("/settings/common_year_related/data", {
          versionId:this.paramVersion.id,
          pageSize: -1
        });
        let dataMap = {};
        if (response.data && response.data.length > 0) {
          for (let item of response.data) {
            dataMap[item.year] = item;
          }
        }
        let yearRelatedInfo = JSON.parse(JSON.stringify(this.yearRelatedList[0]));
        let columns = [{id:'name',name:'项目',width:180,readonly:true}];
        let dataLList = [];
        for (let i = 1; i < 21; i++) {
          columns.push({id:"year" + i , name:"第"+ i +"年"});
          let yearData = dataMap[i];
          if(!yearData || !yearData[yearRelatedInfo.id] ){
            yearRelatedInfo["year" + i] = '';
          }else{
            yearRelatedInfo["year" + i] = yearData[yearRelatedInfo.id] + '';
          }
        }
        dataLList.push(yearRelatedInfo);
        this.yearRelatedColumns = columns;
        this.yearRelatedList = dataLList;
        this.loadingState.yearRelated = false;
      },
      /**
       * 保存数据
       */
      save:function() {
        //获取基准收益率数据
        let unitCostData = [];
        for (const companyInfo of this.officeList) {
          let companyCostData = {};
          let companyId = companyInfo.id;
          companyCostData["companyId"] = companyId;
          for (const unitCostInfo of this.unitCostList) {
            let unitCostInfoElement = unitCostInfo[companyId];
            companyCostData[unitCostInfo.code] = unitCostInfoElement;
          }
          unitCostData.push(companyCostData);
        }
        //获取固定参数数据
        let fixedData = {
          versionId:this.paramVersion.id,
        };
        for (let item of this.taxationDataList) {
          fixedData[item.id] = item.value;
        }
        for (let item of this.fixedCostList) {
          fixedData[item.id] = item.value;
        }
        //获取基准收益率数据
        let baseIrr = [];
        for (let item of this.baseIrrList) {
          let baseIrrInfo = {};
          baseIrrInfo["poolType"] = item.id;
          baseIrrInfo["value"] = item.value;
          baseIrr.push(baseIrrInfo);
        }

        //获取基准收益率数据
        let yearRelatedList = [];
        for (const itemInfo of this.yearRelatedColumns) {
          if(itemInfo.id == "name"){
            continue;
          }
          let yearRelated = {};
          let property = itemInfo.id;
          for (const rowData of this.yearRelatedList) {
            yearRelated["year"] = property.replace("year","");
            yearRelated[rowData.id] = rowData[property];
          }
          yearRelatedList.push(yearRelated);
        }
        const loading = this.openLoading('正在处理，请稍后...');
        this.$post("/settings/common_param_version/data/save", {
          versionId:this.paramVersion.id,
          /**
           * 单位相关数据
           */
          unitCostData:unitCostData,
          /**
           * 固定成本
           */
          fixedData:fixedData,
          /**
           * 基准收益率数据
           */
          baseIrrData:baseIrr,
          /**
           * 年度相关成本
           */
          yearRelatedData:yearRelatedList,
        }, (response) => {
          this.init();
          this.$message.success("保存成功");
        }, () => {
          loading.close();
        });
      },
      /**
       * 发布版本
       */
      publish() {
        this.$confirm('发布后该版本数据将无法编辑与删除, 是否继续?', '提示', {
          confirmButtonText: '发布',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const loading = this.openLoading("正在处理，请稍后");
          this.$post("/settings/common_param_version/publish", this.paramVersion, (response) => {
            this.$message.success('发布成功');
            this.loadParamVersion(this.paramVersion.id);
           //this.$refs['param_query_table'].reload();
            if(this.$route.query.src) {
              let currentPath = this.$route.fullPath;
              this.$emit('tab-refresh',this.$route.query.src,null,()=>{
                this.$emit('tab-active',currentPath)
              })

            }
          }, (response) => {
            loading.close();
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消操作'
          });
        });

      },

      /**
       * 取消发布版本
       */
      unPublish() {
        this.$confirm('是否取消发布此版本, 是否继续?', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const loading = this.openLoading("正在处理，请稍后");
          this.$post("/settings/common_param_version/unPublish", this.paramVersion, (response) => {
            this.$message.success('取消发布成功');
            this.loadParamVersion(this.paramVersion.id);
          }, (response) => {
            loading.close();
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消操作'
          });
        });
      },
    },
  }
</script>
